import React, { Component, useState } from 'react'
import { SearchBar, IndexBar, List } from 'antd-mobile'
import './location.css'
import api from "../../../api/index"
import cityList from "./city.json";
import { connect } from "react-redux";
import { useNavigate } from "react-router-dom"


const groups = cityList.city.map((city, i) => ({
    title: city.initial,
    items: city.list,
}))


function Location(props) {
    const navigate = useNavigate();
    let [hotCity, setHotCity] = useState([]);

    React.useEffect(() => {
        // console.log("这是模拟componentDidMount钩子函数")
        getCity()
        return () => {//return出来的函数本来就是更新前，销毁前执行的函数，现在不监听任何状态，所以只在销毁前执行
            // getCity()
        }
    },[])
    

    async function getCity() {
        let { data } = await api.home.getHotCity()
        setHotCity((hotCity = data))

    }
    let { myCity } = props
    let changeCity = (data) => {
        myCity(data);
        navigate('/home')
    }

    function renderHot() {
        return hotCity.map((city, index) => (
            <li key={index}
                onClick={() => changeCity(city.label)}
            >
                {city.label}
            </li>
        ))
    }

    return (
        <div className="locationBox">
            <header>
                <SearchBar placeholder='请输入城市名' />
            </header>
            <h2>当前定位</h2>
            <ul>
                <li>北京市</li>
            </ul>
            <h2>热门城市</h2>
            <ul>
                {
                    renderHot()
                }
            </ul>
            <div className="cityList">
                <IndexBar>
                    {groups.map(group => {
                        const { title, items } = group
                        return (
                            <IndexBar.Panel
                                index={title}
                                title={`${title}`}
                                key={`${title}`}
                            >
                                <List>
                                    {items.map((item, index) => (
                                        <List.Item key={index}>{item.name}</List.Item>
                                    ))}
                                </List>
                            </IndexBar.Panel>
                        )
                    })}
                </IndexBar>
            </div>
        </div>
    );
}

const mapStateToProps = state => {
    return {
        currentCity: state.city,
        ...state
    };
};
const mapDispatchToProps =(dispatch,oldProps) => {
    return {
        myCity: (data) => {
            // 真正触发修改redux值
            console.log(data);
            
            return dispatch({ type: "changeCity", payload: data })
        }
    }

};

export default connect(mapStateToProps, mapDispatchToProps)(Location);